package com.zy.stock.controller;

import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.User;
import com.zy.stock.domain.UserStockRl;
import com.zy.stock.dto.UserStockRlDto;
import com.zy.stock.dto.UserStockRlProfitDto;
import com.zy.stock.service.StockService;
import com.zy.stock.service.UserService;
import com.zy.stock.service.UserStockRlService;
import com.zy.stock.util.CommonUtils;

@Controller
public class UserStockRlController {
	
	private Logger logger = LoggerFactory.getLogger(UserStockRlController.class);
	
	@Autowired
	private UserStockRlService userStockRlService;
	
	@Autowired
	private StockService stockService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/userStockRlManage")
	public ModelAndView toBillManager() {
		ModelAndView mav = new ModelAndView("userStockRl");
		mav.addObject("menuid",5);
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "getUserStockRlById")
	public String getStockById(HttpServletRequest request) {
		String result = "";
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			UserStockRl entity = userStockRlService.findById(id);
			map.put("data", entity);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "getUserStockRlPage")
	public String getStockPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		String result = "";
		try {
			Integer draw = Integer.parseInt(request.getParameter("draw"));
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer length = Integer.parseInt(request.getParameter("length"));
			String stockName = request.getParameter("stockName");
			String stockCode = request.getParameter("stockCode");
			String years = request.getParameter("years");
			String userName = request.getParameter("userName");
			String orderColumn = request.getParameter("order[0][column]");
			String columnName = request.getParameter("columns[" + orderColumn + "][data]");
			String orderDir = request.getParameter("order[0][dir]");
			Pager<UserStockRlDto> pager = new Pager<>();
			UserStockRlDto dto = new UserStockRlDto();
			dto.setStockName(stockName);
			dto.setStockCode(stockCode);
			dto.setYears(years);
			dto.setUserName(userName);
			pager.setT(dto);
			pager.setPagenow(start / length + 1);
			pager.setSize(length);
			pager.setOrderCol(columnName);
			pager.setOrder(orderDir);
			Pager<List<UserStockRl>> stations = userStockRlService.findByCase(pager);
			map.put("data", stations.getT());
			map.put("recordsTotal", stations.getTotal());
			map.put("recordsFiltered", stations.getTotal());
			map.put("draw", draw);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
		
	@ResponseBody
	@RequestMapping(value = "getRlData")
	public String getRlData(HttpServletRequest request) {
		String result = "";
		try {
		    String stockName = request.getParameter("stockName");
            String stockCode = request.getParameter("stockCode");
            String years = request.getParameter("years");
            String userName = request.getParameter("userName");
            String userId = request.getParameter("userId");
            String total = "";
            String rate = "";
            User user = null;
            UserStockRlDto dto = new UserStockRlDto();
            dto.setStockName(stockName);
            dto.setStockCode(stockCode);
            dto.setYears(years);
            dto.setUserName(userName);
            if(StringUtils.isNotEmpty(userId)){
              dto.setUserId(Integer.parseInt(userId));
              user = userService.findById(Integer.parseInt(userId));
            }
            if(StringUtils.isNotEmpty(userName)){
            	user = userService.findByName(userName);
            	dto.setUserId(user.getId());
            }
            List<UserStockRlProfitDto> profits = userStockRlService.findRlProfit(dto);
            if(profits!=null&&profits.size()>0){
              UserStockRlProfitDto profit = profits.get(0);
              BigDecimal profitBD = new BigDecimal(profit.getProfit());
              profitBD = profitBD.setScale(0, BigDecimal.ROUND_HALF_UP);
              total = String.valueOf(profit.getProfit());
              double earningRate = profit.getProfit()*100/user.getPrincipal();
              BigDecimal earningRateBD = new BigDecimal(earningRate);
              earningRateBD = earningRateBD.setScale(2, BigDecimal.ROUND_HALF_UP);
              rate = (earningRateBD.toString()+"%");
            }
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			map.put("total",total);
			map.put("rate",rate);
            map.put("msg", "succ");
            map.put("code", 0);
            mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@ResponseBody
	@RequestMapping(value = "addUserStockRl")
	public String addUserStockRl(UserStockRl userStockRl, HttpServletRequest request) {
		try {
			//处理账户id
			User user = userService.findByName(userStockRl.getUserName());
			if(user!=null){
				userStockRl.setUserId(user.getId());
			}
			//处理股票id
			List<Stock> stocks = stockService.findByCode(userStockRl.getStockCode());
			if(stocks!=null&&stocks.size()>0){
				userStockRl.setStockId(stocks.get(0).getId());
			}
			//处理仓库编码
			List<UserStockRl> rls = userStockRlService.findLastUserStockRl(user.getId(), stocks.get(0).getId(), userStockRl.getYears());
			if(rls!=null&&rls.size()>0){
				UserStockRl rl = rls.get(0);
				String storeNum = rl.getStoreNum();
				String [] arr = storeNum.split("_");
				String lastNum = arr[arr.length-1];
				Integer newNum = Integer.valueOf(lastNum)+1;
				logger.info("new storeNum is"+arr[0]+"_"+arr[1]+"_"+arr[2]+"_"+String.valueOf(newNum));
				userStockRl.setStoreNum(arr[0]+"_"+arr[1]+"_"+arr[2]+"_"+String.valueOf(newNum));
			}else{
				logger.info("new storeNum is"+user.getId()+"_"+stocks.get(0).getCode()+"_"+userStockRl.getYears()+"_1");
				userStockRl.setStoreNum(user.getName()+"_"+stocks.get(0).getName()+"_"+userStockRl.getYears()+"_1");
			}
			userStockRlService.save(userStockRl);
		} catch (Exception e) {
			e.printStackTrace();
			return CommonUtils.resultJsonString(-1, "error");
		} finally {
			
		}
		return CommonUtils.resultJsonString(0, "succ");
	}
	
	@ResponseBody
	@RequestMapping(value = "updateUserStockRl")
	public Integer updateStock(UserStockRl userStockRl, HttpServletRequest request) {
		try {
			userStockRlService.update(userStockRl);
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value = "deleteUserStockRlById")
	public Integer deleteStockById(HttpServletRequest request) {
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			userStockRlService.deleteById(id);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
	}
	
	@ResponseBody
    @RequestMapping(value = "addUserRlShare")
    public Integer addUserRlShare(HttpServletRequest request) {
        try {
            Integer baseStockNum =  null;
            if(StringUtils.isNotEmpty(request.getParameter("baseStockNum"))){
                baseStockNum = Integer.parseInt(request.getParameter("baseStockNum"));
            }
            
            Integer shareStockNum = null;
            if(StringUtils.isNotEmpty(request.getParameter("shareStockNum"))){
                shareStockNum = Integer.parseInt(request.getParameter("shareStockNum"));
            }
            
            Integer baseCashNum = null;
            if(StringUtils.isNotEmpty(request.getParameter("baseCashNum"))){
                baseCashNum = Integer.parseInt(request.getParameter("baseCashNum"));
            }
            
            Double shareCash = null;
            if(StringUtils.isNotEmpty(request.getParameter("shareCash"))){
                shareCash = Double.parseDouble(request.getParameter("shareCash"));
            }
            
            Integer stockId = Integer.parseInt(request.getParameter("id"));
            stockService.dealUserRlShare(baseStockNum, shareStockNum, baseCashNum, shareCash, stockId);
            return 0;
        } catch (Exception e) {
            logger.error(e.toString());
            return -1;
        } finally {
            
        }
    }
	
	@ResponseBody
	@RequestMapping(value = "addShare")
	public Integer addShare(HttpServletRequest request) {
		try {
			Integer baseStockNum =  null;
			if(StringUtils.isNotEmpty(request.getParameter("baseStockNum"))){
				baseStockNum = Integer.parseInt(request.getParameter("baseStockNum"));
			}
			
			Integer shareStockNum = null;
			if(StringUtils.isNotEmpty(request.getParameter("shareStockNum"))){
				shareStockNum = Integer.parseInt(request.getParameter("shareStockNum"));
			}
			
			Integer baseCashNum = null;
			if(StringUtils.isNotEmpty(request.getParameter("baseCashNum"))){
				baseCashNum = Integer.parseInt(request.getParameter("baseCashNum"));
			}
			
			Double shareCash = null;
			if(StringUtils.isNotEmpty(request.getParameter("shareCash"))){
				shareCash = Double.parseDouble(request.getParameter("shareCash"));
			}
			
			Integer stockId = Integer.parseInt(request.getParameter("id"));
			stockService.dealShare(baseStockNum, shareStockNum, baseCashNum, shareCash, stockId);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
	}
}
